import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import com.totalvalidator.sgml.RealAttribute;
import com.totalvalidator.sgml.Tag;


public class AExtractor implements Extractor {

	public boolean extract(List<Tag> tags, String extractor) {
		boolean result = false;
		String multi = "false";
		String element = "a";
		String attributes = "";
		String para = "";
		Hashtable<String, String> attrs = new Hashtable<String, String>();
		Hashtable<String,String> queryHash = new Hashtable<String,String>();
		
		java.util.StringTokenizer tokens = new java.util.StringTokenizer(extractor,";=");
		while(tokens.hasMoreElements()){
			String token = tokens.nextToken();
            if(token.equalsIgnoreCase("condition")){
				attributes = tokens.nextToken();
			}else if(token.equalsIgnoreCase("para")){
				para = tokens.nextToken();
			}
		}
		if(attributes.length()>0){
			tokens = new java.util.StringTokenizer(attributes,"{},");
			while(tokens.hasMoreElements()){
				attrs.put(tokens.nextToken(), tokens.nextToken());
			}
		}
				
		for(int i=0; i< tags.size(); i++){
			Tag tag = (Tag)tags.get(i);
			Map map = tag.getAttributes();
			if(map==null){
				continue;
			}
			boolean isfind = false;
			if(element.equalsIgnoreCase(tag.getElement(false))){
				isfind = true;
				Object query = map.get("href");
				if(query==null){
					continue;
				}
				if(RealAttribute.class.isInstance(query)){
					RealAttribute realAttr = (RealAttribute)query;
					String queryStr = realAttr.getValue();
					if(queryStr.indexOf("?")==-1){
						continue;
					}
					queryStr = queryStr.substring(queryStr.indexOf("?")+1);
					StringTokenizer querytokens = new StringTokenizer(queryStr, "&");
					while (querytokens.hasMoreTokens()) {
						String token = querytokens.nextToken();
						int pos = token.indexOf("=");
						String querykey = token;
						String queryvalue = "";
						try {
							querykey = token.substring(0, pos);
							queryvalue = token.substring(pos + 1);

						} catch (Exception me) {

						}
						queryHash.put(querykey, queryvalue);
					}					
				}
				
				java.util.Enumeration en = attrs.keys();
				while(en.hasMoreElements()){
					String k = (String)en.nextElement();
					String v = attrs.get(k);
					Object obj = map.get(k);
					if(obj==null){
						isfind = false;
						break;
					}
					if(RealAttribute.class.isInstance(obj)){
						RealAttribute realAttr = (RealAttribute)obj;
						if(realAttr.getValue().indexOf(v)==-1){
							isfind = false;
							break;
						}
					}
				}
			}
			if(isfind){
				String value = queryHash.get(para);
				System.out.println("extract data:"+para+","+value);
				PlayData.addSessionData(para, value);
				result = true;
				if(multi.equalsIgnoreCase("false")){
					return true;
				}
			}
		}
		return result;
	}

}
